let net = require('net');
let CumulationID = require('./id_alloter').CumulationID;

class SocketServer {
    constructor(port, ip='0.0.0.0'){
        this.listenPort = port;//监听端口
        this.listenIp = ip;
        this.server = net.createServer();
        this.ids = new CumulationID();
        this.mapIds = new Map();
        this.ids.init(5, 200000000);

        //服务器监听事件
        this.server.on('listening',function(){
            if (global.log) {
                global.log.print("server listening:" + this.address().port);
            } else {
                console.log("server listening:" + this.address().port);
            }
        });
        //服务器错误事件
        this.server.on("error",function(exception){
            if (global.log) {
                global.log.error("server error " + exception);
            } else {
                console.error("server error " + exception);
            }
        });
        //服务器关闭事件
        this.server.on("close",function(exception){
            if (global.log) {
                global.log.print("server close " + exception);
            } else {
                console.log("server close " + exception);
            }
        });
    }
    //启动
    startListen(connectCallback, errorCallback, recvCallback, closeCallback){
        this.server.listen(this.listenPort, this.listenIp);

        let self = this;
        //连接创建后事件
        this.server.on("connection",function(socket){
            // 创建socket服务端
            // console.log('new client: ' + socket.remoteAddress + ':' + socket.remotePort);
            socket.setEncoding('binary');

            //接收到数据
            socket.on('data',function(data){
                //console.log('client send:' + data);
                if (recvCallback) {
                    recvCallback(this, data);
                }
            });
            //socket.write('Hello client!\r\n');
            // socket.pipe(socket);
            //数据错误事件
            socket.on('error',function(exception){
                if (global.log) {
                    global.log.error("socket error " + exception);
                } else {
                    console.error("socket error " + exception);
                }
                if (errorCallback) {
                    errorCallback(this, exception);
                }
                socket.end();
            });
            //客户端关闭事件
            socket.on('close',function(had_error){
                // console.log('client closed: '+socket.remoteAddress + ':' + socket.remotePort);
                if (closeCallback) {
                    closeCallback(this, had_error);
                }
                self.mapIds.delete(socket.conn_id);
            });
            socket.conn_id = self.ids.getID();
            self.mapIds.set(socket.conn_id, socket);
            if (connectCallback) {
                connectCallback(socket);
            }
        });
    }
    //关闭，服务器停止接收新的连接，保持现有连接。这是异步函数，当所有连接结束的时候服务器会关闭，并会触发 'close' 事件。
    waitClose(){
        this.server.close();
    }
    findSocket(connId){
        return this.mapIds.get(connId);
    }
    send(connId, data){
        let socket = this.mapIds.get(connId);
        if (socket) {
            try {
				socket.write(data);
				return true;
			} catch (err) {
				if (global.log) {
					global.log.error("socket error "+err);
				} else {
					console.error("socket error "+err);
				}
				return false;
			}
        }
        return false;
    }
}

module.exports = SocketServer;